package com.borrow.jiemihua.mainUI.activity;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.borrow.jiemihua.R;
import com.borrow.jiemihua.base.BaseActivity;
import com.borrow.jiemihua.base.BaseConstant;
import com.borrow.jiemihua.base.BaseRVAdapter;
import com.borrow.jiemihua.base.BaseViewHolder;
import com.borrow.jiemihua.base.URLConstant;
import com.borrow.jiemihua.bean.GoldLinkBean;
import com.borrow.jiemihua.dialog.iosdialog.ActionSheetDialog;
import com.borrow.jiemihua.utils.SharedPreferencesUtils;
import com.borrow.jiemihua.utils.xutils3.MyCallBack;
import com.borrow.jiemihua.utils.xutils3.XUtil;
import com.borrow.jiemihua.view.pull.PullLoadMoreRecyclerView;
import com.google.gson.Gson;
import com.tencent.mm.sdk.modelmsg.SendMessageToWX;
import com.tencent.mm.sdk.modelmsg.WXMediaMessage;
import com.tencent.mm.sdk.modelmsg.WXWebpageObject;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cc.duduhuo.custoast.CusToast;

public class InvitePrizeActivity extends BaseActivity implements View.OnClickListener{
    private TextView tv_top_title;
    private PullLoadMoreRecyclerView recyclerView;
    private View head;
    private TextView tv_my_invite,tv_invite_bt;
    private IWXAPI wxAPI;
    private String APP_ID = "wxd719b80668fd74ab";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_invite_prize);
        head= View.inflate(InvitePrizeActivity.this,R.layout.activity_invite_head, null);
        wxAPI = WXAPIFactory.createWXAPI(InvitePrizeActivity.this, APP_ID,true);
        wxAPI.registerApp(APP_ID);
        initData();
        initView();
        upCKYQMData();
        initRecyclerData();
    }

    @Override
    protected void initData() {
        findViewById(R.id.imgbtn_left).setOnClickListener(this);
        tv_top_title= (TextView) findViewById(R.id.tv_top_title);
        tv_top_title.setText("积分明细");
    }

    @Override
    protected void initView() {
        recyclerView= (PullLoadMoreRecyclerView) findViewById(R.id.recyclerView);
        recyclerView.setLinearLayout();
        tv_invite_bt= (TextView) head.findViewById(R.id.tv_invite_bt);
        tv_my_invite= (TextView) head.findViewById(R.id.tv_my_invite);
        head.findViewById(R.id.tv_invite_bt).setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.imgbtn_left:
                finish();
                break;
            case R.id.tv_invite_bt:
                upYQData();
                break;
            default:break;

        }
    }
    private BaseRVAdapter rvAdapter;
    private void initRecyclerData(){
        rvAdapter= new BaseRVAdapter(this,dataBeanList) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.invite_prize_recycleritem;
            }

            @Override
            public void onBind(BaseViewHolder holder, final int position) {
                ImageView iv_link=holder.getImageView(R.id.iv_link);
                if(position==0){
                    iv_link.setImageResource(R.drawable.me_league_table_first);
                }else if(position==1){
                    iv_link.setImageResource(R.drawable.me_league_table_second);
                }else if(position==2){
                    iv_link.setImageResource(R.drawable.me_league_table_third);
                }else{
                    int i=position+1;
                    holder.getTextView(R.id.tv_link).setText(i+"");
                }

                String str=dataBeanList.get(position).getCellphone()+"";
                if(!str.equals("")){
                    if (str.length()>9){
                        StringBuilder builder=new StringBuilder(str);
                        builder.replace(3,7,"****");
                        holder.getTextView(R.id.tv_title).setText(builder.toString());
                    }
                }

                holder.getTextView(R.id.tv_glod).setText(dataBeanList.get(position).getGold()+"");
                if(position<=2){
                    holder.getTextView(R.id.tv_link).setVisibility(View.GONE);
                    holder.getImageView(R.id.iv_link).setVisibility(View.VISIBLE);
                    holder.getTextView(R.id.tv_glod).setTextColor(getResources().getColor(R.color.my_text_red));
                }else{
                    holder.getTextView(R.id.tv_link).setVisibility(View.VISIBLE);
                    holder.getImageView(R.id.iv_link).setVisibility(View.GONE);
                    holder.getTextView(R.id.tv_glod).setTextColor(getResources().getColor(R.color.text_6));
                }

            }
        };
        recyclerView.setAdapter(rvAdapter);
        rvAdapter.addHeaderView(head);
        upGoldLinkData(1);
        recyclerView.setOnPullLoadMoreListener(new PullLoadMoreRecyclerView.PullLoadMoreListener() {
            @Override
            public void onRefresh() {
                upGoldLinkData(1);
            }

            @Override
            public void onLoadMore() {
                upGoldLinkData(2);
            }
        });
    }
    @Override
    protected void onResume() {
        super.onResume();
        upGoldLinkData(1);
    }

    private int page;
    private List<GoldLinkBean.DataBean> dataBeanList =new ArrayList<>();
    private void upGoldLinkData(final int i){
        Map<String, String> map = new HashMap<>();
//        String userid = SharedPreferencesUtils.getString(this, BaseConstant.SPConstant.USERID, "");
//        map.put("userId",userid);
        if (i == 1) {
            page = 1;
        } else {
            page++;
        }
        map.put("page", page+"");
        map.put("pageSize", 10+"");
        XUtil.Get(URLConstant.GOLD_LINKINVITR,map,new MyCallBack<String>(){
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.i("==积分排行榜",result);
                try {
                    JSONObject jsonObject=new JSONObject(result);
                    if(jsonObject.optString("isSuccess").equals("1")) {
                        Gson gson = new Gson();
                        GoldLinkBean goldLinkBean = gson.fromJson(result, GoldLinkBean.class);
                        List<GoldLinkBean.DataBean>  dataBeanList1 = goldLinkBean.getData();
                        if (i == 1) {
                            dataBeanList.clear();
                        }

                        dataBeanList.addAll(dataBeanList1);
                        rvAdapter.notifyDataSetChanged();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
                recyclerView.setPullLoadMoreCompleted();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                ex.printStackTrace();
            }
        });

    }
    private void upCKYQMData(){
        Map<String, String> map = new HashMap<>();
        String userid = SharedPreferencesUtils.getString(this, BaseConstant.SPConstant.USERID, "");
        map.put("userId",userid);
        showDialog();
        XUtil.Get(URLConstant.KOOK_INVITR,map,new MyCallBack<String>(){
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.i("==查看邀请码",result);
                try {
                    JSONObject jsonObject=new JSONObject(result);
                    if(jsonObject.optString("isSuccess").equals("1")) {
                        String data=jsonObject.optString("data");
                        tv_my_invite.setText(data);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
                closeDialog();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                ex.printStackTrace();
                closeDialog();
            }
        });
    }
    private void upYQData(){
        Map<String, String> map = new HashMap<>();
        String userid = SharedPreferencesUtils.getString(this, BaseConstant.SPConstant.USERID, "");
        map.put("userId",userid);
        map.put("packet","Android");
        showDialog();
        XUtil.Get(URLConstant.YAOQINGHAOYOU,map,new MyCallBack<String>(){
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.i("==查看邀请码",result);
                try {
                    JSONObject jsonObject=new JSONObject(result);
                    if (jsonObject.optString("isSuccess").equals("1")) {
                        String data=jsonObject.optString("data");
                        JSONObject Object = new JSONObject(data);
                        content=Object.optString("content");
                        linkUrl=URLConstant.URL+Object.optString("linkUrl");
                        title=Object.optString("title");
                        share();
                    }else{
                        CusToast.showToast("分享错误");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
                closeDialog();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                ex.printStackTrace();
                closeDialog();
            }
        });
    }
    private String  content;
    private String  linkUrl;
    private String  title;
    private void share(){
        new ActionSheetDialog(this)
                .builder()
                .setCancelable(false)
                .setCanceledOnTouchOutside(false)
                .addSheetItem("微信朋友圈", ActionSheetDialog.SheetItemColor.Blue,
                        new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
//                                Log.i("=======温馨1111",linkUrl);

                                WXWebpageObject webpage = new WXWebpageObject();
                                webpage.webpageUrl = linkUrl;//分享url
                                WXMediaMessage msg = new WXMediaMessage(webpage);
                                msg.title = title;
                                msg.description = content;
                                Bitmap thumb = BitmapFactory.decodeResource(getResources(), R.mipmap.logo);
                                msg.thumbData =bmpToByteArray(thumb);//封面图片byte数组
                                SendMessageToWX.Req req = new SendMessageToWX.Req();
                                req.transaction = String.valueOf(System.currentTimeMillis());
                                req.message = msg;
                                req.scene = SendMessageToWX.Req.WXSceneTimeline;//朋友圈
                                wxAPI.sendReq(req);

                            }
                        })
                .addSheetItem("微信好友", ActionSheetDialog.SheetItemColor.Blue,
                        new ActionSheetDialog.OnSheetItemClickListener() {
                            @Override
                            public void onClick(int which) {
                                Log.i("=======温馨3333",linkUrl);
                                WXWebpageObject webpage = new WXWebpageObject();
                                webpage.webpageUrl = linkUrl;//分享url
                                WXMediaMessage msg = new WXMediaMessage(webpage);
                                msg.title = title;
                                msg.description = content;
                                Bitmap thumb = BitmapFactory.decodeResource(getResources(), R.mipmap.logo);
                                msg.thumbData =bmpToByteArray(thumb);//封面图片byte数组
                                SendMessageToWX.Req req = new SendMessageToWX.Req();
                                req.transaction = String.valueOf(System.currentTimeMillis());
                                req.message = msg;
                                req.scene = SendMessageToWX.Req.WXSceneSession;//好友
                                wxAPI.sendReq(req);

                            }
                        }).show();
    }
    /**
     * 得到Bitmap的byte
     *
     * @param bmp 图片
     * @return 返回压缩的图片
     */
    private static byte[] bmpToByteArray(Bitmap bmp) {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.PNG, 100, output);

        byte[] result = output.toByteArray();
        try {
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}
